package com.lzy.business.facade;

import com.github.pagehelper.PageInfo;
import com.lzy.base.dtos.SysIdentityDto;
import com.lzy.business.multiple.MultipleDatasourceService;
import com.lzy.framework.common.dtos.LicenseDto;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.utils.StringUtil;
import com.lzy.product.apis.*;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by WIN7 on 2017/12/1.
 */
@Component
public class ProductInfoFacade {
    @Autowired
    ProductInfoServiceApi productInfoServiceApi;

    @Autowired
    ProductInfoClassifyServiceApi productInfoClassifyServiceApi;

    @Autowired
    ProductClassifyServiceApi productClassifyServiceApi;

    @Autowired
    ProductInfoProjectServiceApi productInfoProjectServiceApi;

    @Autowired
    ProductImageTextServiceApi productImageTextServiceApi;

    @Autowired
    ProjectServiceApi projectServiceApi;

    @Resource
    MultipleDatasourceService multipleDatasourceService;

    /**
     * 批量上下架
     */
    public Boolean upDownList(Long[] idList, Integer shelves) {
        String ids = "";
        Integer n = 0;
        for (Long id : idList) {
            ids = ids + id + ",";
            n++;
        }
        ids = ids.substring(0, ids.length() - 1);
        Integer m = productInfoServiceApi.updateList(shelves, ids);
        Ensure.that(m.equals(n)).isTrue("01000009");
        return true;
    }

    /**
     * 获取产品列表
     */
    public PageInfo<ProductInfoDto> select(Pager pager, ProductInfoDto dto) {
        Ensure.that(pager).isNotNull("01000003");
        Ensure.that(dto).isNotNull("01000003");
        dto.setType(BusinessType.ProductType.MEAL.getCode());
        PageInfo<ProductInfoDto> pageInfo = productInfoServiceApi.selectList(pager, dto);
        if (pageInfo != null && pageInfo.getList().size() > 0) {
            for (ProductInfoDto piDto : pageInfo.getList()) {
                Ensure.that(piDto).isNotNull("01000002");
                ProductInfoClassifyDto productInfoClassifyDto = new ProductInfoClassifyDto();
                productInfoClassifyDto.setInfoId(piDto.getId());
                List<ProductInfoClassifyDto> classifyList = productInfoClassifyServiceApi.selectList(productInfoClassifyDto);
                if (classifyList != null && classifyList.size() > 0) {
                    String classifyName = "";
                    for (ProductInfoClassifyDto classifyDto : classifyList) {
                        Ensure.that(classifyDto).isNotNull("02000002");
                        Ensure.that(classifyDto.getClassifyId()).isNotNull("02000002");
                        ProductClassifyDto productClassifyDto = productClassifyServiceApi.findById(classifyDto.getClassifyId());
                        classifyName = classifyName + productClassifyDto.getName() + "/";
                    }
                    classifyName = classifyName.substring(0, classifyName.length() - 1);
                    piDto.setClassifyName(classifyName);
                }
            }
        }
        return pageInfo;
    }

    /**
     * 新增产品
     */
    public Boolean insert(ProductInfoDto dto,String[] param) {
        Ensure.that(dto).isNotNull("01000003");
        // 审核
        LicenseDto lic = new LicenseDto();
        lic.setUrl("/admin/product/info/view/");
        lic.setCode("sys:product:add");
        //添加产品
        Long b = productInfoServiceApi.addProduct(dto,param,lic);
        Ensure.that(b).isNotNull("01000001");
        //添加图文详情
        List<ProductImageTextDto> productImageTextDtoList = dto.getDetailImages();
        if (productImageTextDtoList != null && productImageTextDtoList.size() > 0) {
            int i = 0;
            for (ProductImageTextDto productImageText : productImageTextDtoList) {
                if (null == productImageText || StringUtil.isBlank(productImageText.getPath())) {
                    continue;
                }
                i++;
                productImageText.setProductId(b);
                productImageText.setSort(i);
                productImageText.setStatus(BusinessType.StatusEnum.ENABLED.getCode());
                productImageText.setRemark("产品管理, 第" + i + "个图文");
                Long l = productImageTextServiceApi.insert(productImageText);
                Ensure.that(l).isNotNull("01000010");
            }
        }
        //添加产品分类关系
        if(dto.getClassifyId() != null) {
            ProductInfoClassifyDto picDto = new ProductInfoClassifyDto();
            picDto.setInfoId(b);
            picDto.setClassifyId(dto.getClassifyId());
            Long c = productInfoClassifyServiceApi.insert(picDto);
            Ensure.that(b).isNotNull("02000008");
        }
        //添加产品与产品包含项的关系
        List<ProductInfoProjectDto> productProjectList = dto.getProjectList();
        if (productProjectList != null && productProjectList.size() > 0) {
            for (ProductInfoProjectDto ptDto : productProjectList) {
                if (ptDto != null && ptDto.getProjectId() != null) {
                    Ensure.that(ptDto).isNotNull("01000003");
                    Ensure.that(ptDto.getProjectId()).isNotNull("01000003");
                    Ensure.that(ptDto.getContainNum()).isNotNull("01000003");
                    Ensure.that(ptDto.getType()).isNotNull("01000003");
                    //添加产品与分类关系
                    ProductInfoProjectDto pipDto = new ProductInfoProjectDto();
                    pipDto.setProductId(b);
                    pipDto.setProjectId(ptDto.getProjectId());
                    pipDto.setContainNum(Integer.valueOf(ptDto.getContainNum()));
                    pipDto.setType(ptDto.getType());
                    if(ptDto.getValidTime() != null) {
                        pipDto.setValidTime(ptDto.getValidTime());
                    }
                    Long k = productInfoProjectServiceApi.insert(pipDto);
                    Ensure.that(k.equals(0)).isFalse("01000011");
                }
            }
        }
        return true;
    }

    /**
     * 编辑产品
     */
    public Boolean update(ProductInfoDto dto,String[] param) {
        Ensure.that(dto).isNotNull("01000003");
        //审核
        LicenseDto lic = new LicenseDto();
        lic.setUrl("/admin/product/info/view/");
        lic.setCode("sys:product:update");
        //更新产品
        Boolean b = productInfoServiceApi.updateProduct(dto,param,lic);
        Ensure.that(b).isTrue("01000007");
        //先删除图文详情，在新增图文详情
        //删除图文详情
        ProductImageTextDto imageTextDto = new ProductImageTextDto();
        imageTextDto.setProductId(dto.getId());
        List<ProductImageTextDto> imageTextDtoList = productImageTextServiceApi.query(imageTextDto);
        for (ProductImageTextDto pitDto : imageTextDtoList) {
            if (pitDto != null && pitDto.getId() != null) {
                Boolean d = productImageTextServiceApi.delete(pitDto.getId());
                Ensure.that(d).isTrue("01000012");
            }
        }
        //添加图文详情
        List<ProductImageTextDto> productImageTextDtoList = dto.getDetailImages();
        if (productImageTextDtoList != null && productImageTextDtoList.size() > 0) {
            int i = 0;
            for (ProductImageTextDto productImageText : productImageTextDtoList) {
                if (null == productImageText || StringUtil.isBlank(productImageText.getPath())) {
                    continue;
                }
                i++;
                productImageText.setProductId(dto.getId());
                productImageText.setSort(i);
                productImageText.setStatus(BusinessType.StatusEnum.ENABLED.getCode());
                productImageText.setRemark("产品管理, 第" + i + "个图文");
                Long n = productImageTextServiceApi.insert(productImageText);
                Ensure.that(n.equals(0)).isFalse("01000010");
            }
        }

        //更新产品分类关系（有则更新，无则添加）
        ProductInfoClassifyDto picDto = new ProductInfoClassifyDto();
        picDto.setInfoId(dto.getId());
        ProductInfoClassifyDto productInfoClassifyDto = productInfoClassifyServiceApi.selectProductClassify(picDto);
        if(dto.getClassifyId() != null) {
            picDto.setClassifyId(dto.getClassifyId());
            //无则添加
            if (productInfoClassifyDto == null) {
                Long m = productInfoClassifyServiceApi.insert(picDto);
                Ensure.that(m.equals(0)).isFalse("01000011");

            } else if (productInfoClassifyDto != null) {
                //有则更新
                Boolean bl = productInfoClassifyServiceApi.updateByKey(picDto);
                Ensure.that(bl).isTrue("01000013");
            }
        }else{
            //如果分类id为空，则判断有没有关联关系，有则删除
            if(productInfoClassifyDto != null){
                Boolean bk = productInfoClassifyServiceApi.deleteProductInfoClassify(picDto);
                Ensure.that(bk).isTrue("01000020");
            }

        }
            //添加产品与产品包含项的关系
            //先删除关系
            ProductInfoProjectDto productInfoProjectDto = new ProductInfoProjectDto();
            productInfoProjectDto.setProductId(dto.getId());
            List<ProductInfoProjectDto> infoProjectDtoList = productInfoProjectServiceApi.query(productInfoProjectDto);
            Ensure.that(infoProjectDtoList).isNotNull("01000014");
            if (infoProjectDtoList != null && infoProjectDtoList.size() > 0) {
                Integer i = productInfoProjectServiceApi.deleteByProductId(productInfoProjectDto);
                Ensure.that(i.equals(infoProjectDtoList.size())).isTrue("01000015");
            }
            //创建关系
            List<ProductInfoProjectDto> productProjectList = dto.getProjectList();
            if (productProjectList != null && productProjectList.size() > 0) {
                for (ProductInfoProjectDto ptDto : productProjectList) {
                    if (ptDto != null && ptDto.getProjectId() != null) {
                        Ensure.that(ptDto).isNotNull("01000003");
                        Ensure.that(ptDto.getProjectId()).isNotNull("01000003");
                        Ensure.that(ptDto.getContainNum()).isNotNull("01000003");
                        Ensure.that(ptDto.getType()).isNotNull("01000003");
                        //添加产品与分类关系
                        ProductInfoProjectDto pipDto = new ProductInfoProjectDto();
                        pipDto.setProductId(dto.getId());
                        pipDto.setProjectId(ptDto.getProjectId());
                        pipDto.setContainNum(Integer.valueOf(ptDto.getContainNum()));
                        pipDto.setType(ptDto.getType());
                        if(ptDto.getValidTime() != null){
                            pipDto.setValidTime(ptDto.getValidTime());
                        }
                        Long e = productInfoProjectServiceApi.insert(pipDto);
                        Ensure.that(e.equals(0)).isFalse("01000016");
                    }
                }
            }
            return true;
        }

    public List<ProductInfoProjectDto> selectSysIdentityByProductInfo(ProductInfoDto productInfoDto) {
        //获取产品包含项信息
        List<ProductInfoProjectDto> pipDtoList = new ArrayList<>();
        if (productInfoDto.getId() != null) {
            ProductInfoProjectDto pipDto = new ProductInfoProjectDto();
            pipDto.setProductId(productInfoDto.getId());
            pipDtoList = productInfoProjectServiceApi.query(pipDto);
            Ensure.that(pipDtoList).isNotNull("01000014");
        }
        //查询产品包含项
        ProjectDto projectDto = new ProjectDto();
        projectDto.setBusiType(BusinessType.OrderProductType.PRODUCT.getCode());
        PageInfo<ProjectDto> pageInfo  = projectServiceApi.queryList(null,projectDto);
        Ensure.that(pageInfo).isNotNull("01000006");
        Ensure.that(pageInfo.getList()).isNotNull("01000006");

        //整合成一个list
        List<ProductInfoProjectDto> proProjectList = new ArrayList<>();
        List<ProjectDto> projectDtoList = pageInfo.getList();
        //先保存所有包含项信息，去除和关联项信息的共有信息
        List<ProjectDto> proList = new ArrayList<>();
        for (ProjectDto p : projectDtoList) {
            proList.add(p);
        }
        for (ProjectDto pDto : projectDtoList) {
            for (ProductInfoProjectDto pipDTO : pipDtoList) {
                if (pDto.getId().equals(pipDTO.getProjectId())) {
                    pipDTO.setUnit(pDto.getUnit());
                    pipDTO.setName(pDto.getName());
                    proProjectList.add(pipDTO);
                    proList.remove(pDto);
                }
            }
        }
        //将不公有信息放入返回的list中
        for (ProjectDto proDto : proList) {
            ProductInfoProjectDto infoProjectDto = new ProductInfoProjectDto();
            infoProjectDto.setUnit(proDto.getUnit());
            infoProjectDto.setName(proDto.getName());
            infoProjectDto.setProjectId(proDto.getId());
            proProjectList.add(infoProjectDto);
        }
        return proProjectList;
    }

    public ProductInfoDto findById(Long id) {
        ProductInfoDto productInfoDto = productInfoServiceApi.findById(id);
        if (productInfoDto != null) {
            //获取产品身份信息
            if (productInfoDto.getIdentityId() != null && !productInfoDto.getIdentityId().equals(0)) {
                SysIdentityDto sysIdentityDto = multipleDatasourceService.getById(Long.valueOf(productInfoDto.getIdentityId()));
                if (sysIdentityDto != null) {
                    productInfoDto.setIdentityName(sysIdentityDto.getName());
                }
            }
            return productInfoDto;
        }
        return null;
    }
}
